<!-- 控件-右键菜单 -->
<template>
    <Teleport to="body">
        <div
            v-if="visible"
            ref="contextmenuRef"
            class="contextmenu"
            :style="style"
        >
            <div class="contextmenu-item" @click="onCopy()">
                <el-icon><icon-copy /></el-icon>
                <span>复制</span>
                <div class="tip-txt">Ctrl + C</div>
                
                <template v-if="isOneLevelWidget">
                    <div class="rigth-icon">
                        <el-icon><icon-arrow-right /></el-icon>
                    </div>
                    <div v-if="pageList.length" class="contextmenu-submenu">
                        <el-scrollbar max-height="200px">
                            <template v-for="(element, index) in pageList" :key="index">
                                <div class="contextmenu-item" @click.stop="onCopy(element.router)">
                                    <span>{{ element.name }}</span>
                                    <div v-if="pageId === element.router" class="titel-tip">(当前页)</div>
                                </div>
                                <div v-if="index !== pageList.length - 1" class="contextmenu-divider"></div>
                            </template>
                        </el-scrollbar>
                    </div>
                </template>
            </div>
            <div class="contextmenu-divider"></div>

            <div class="contextmenu-item" @click="onDelete">
                <el-icon><icon-delete /></el-icon>
                <span>删除</span>
                <div class="tip-txt">Delete</div>
            </div>
            <div class="contextmenu-divider"></div>

            <template v-if="isFreeWidget">
                <template v-if="!isTop || !isBottom">
                    <div v-if="!isTop" class="contextmenu-item" @click="onTopOrBottom(true)">
                        <el-icon><icon-top /></el-icon>
                        <span>置顶</span>
                        <div class="tip-txt">Ctrl + Shift + ↑</div>
                    </div>
                    <div v-if="!isBottom" class="contextmenu-item" @click="onTopOrBottom(false)">
                        <el-icon><icon-bottom /></el-icon>
                        <span>置底</span>
                        <div class="tip-txt">Ctrl + Shift + ↓</div>
                    </div>
                    <div v-if="!isTop" class="contextmenu-item" @click="onTopOneOrBottomOne(true)">
                        <el-icon><icon-one-top /></el-icon>
                        <span>上移一层</span>
                        <div class="tip-txt">Ctrl + ↑</div>
                    </div>
                    <div v-if="!isBottom" class="contextmenu-item" @click="onTopOneOrBottomOne(false)">
                        <el-icon><icon-one-bottom /></el-icon>
                        <span>下移一层</span>
                        <div class="tip-txt">Ctrl + ↓</div>
                    </div>
                    <div class="contextmenu-divider"></div>
                </template>
                <!-- <div v-if="!isLock" class="contextmenu-item" @click="onLockOrUnLock(true)">
                    <el-icon><icon-lock /></el-icon>
                    <span>锁定</span>
                </div>
                <div v-else class="contextmenu-item" @click="onLockOrUnLock(false)">
                    <el-icon><icon-un-lock /></el-icon>
                    <span>解锁</span>
                </div>
                <div class="contextmenu-divider"></div> -->
            </template>

            <div class="contextmenu-item" @click="onAnimation">
                <el-icon><icon-animation /></el-icon>
                <span>动画</span>
            </div>

            <template v-if="!['suspension', 'new-suspension', 'custom-top-nav', 'bbs', 'popup-window'].includes(widgetType)">
                <div class="contextmenu-divider"></div>
                <div class="contextmenu-item">
                    <span>对齐</span>
                    <div class="rigth-icon">
                        <el-icon><icon-arrow-right /></el-icon>
                    </div>
                    <div
                        class="contextmenu-submenu"
                        style="top:auto;bottom:-6px;"
                    >
                        <el-scrollbar max-height="200px">
                            <div class="contextmenu-item" @click="onSetAlign('left')">
                                <el-icon><icon-align-left /></el-icon>
                                <span>左对齐</span>
                            </div>
                            <div class="contextmenu-divider"></div>
                            <div class="contextmenu-item" @click="onSetAlign('vertical')">
                                <el-icon><icon-align-vertical /></el-icon>
                                <span>水平居中</span>
                            </div>
                            <div class="contextmenu-divider"></div>
                            <div class="contextmenu-item" @click="onSetAlign('right')">
                                <el-icon><icon-align-right /></el-icon>
                                <span>右对齐</span>
                            </div>
                            <template v-if="isFreeWidget">
                                <div class="contextmenu-divider"></div>
                                <div class="contextmenu-item" @click="onSetAlign('top')">
                                    <el-icon><icon-align-top /></el-icon>
                                    <span>顶对齐</span>
                                </div>
                                <div class="contextmenu-divider"></div>
                                <div class="contextmenu-item" @click="onSetAlign('horizontal')">
                                    <el-icon><icon-align-horizontal /></el-icon>
                                    <span>垂直居中</span>
                                </div>
                                <div class="contextmenu-divider"></div>
                                <div class="contextmenu-item" @click="onSetAlign('bottom')">
                                    <el-icon><icon-align-bottom /></el-icon>
                                    <span>底对齐</span>
                                </div>
                                <div class="contextmenu-divider"></div>
                                <div class="contextmenu-item" @click="onSetAlign('horizontalEquidistant')">
                                    <el-icon><icon-horizontal-equidistant /></el-icon>
                                    <span>水平等间距</span>
                                </div>
                                <div class="contextmenu-divider"></div>
                                <div class="contextmenu-item" @click="onSetAlign('verticalEquidistant')">
                                    <el-icon><icon-vertical-equidistant /></el-icon>
                                    <span>垂直等间距</span>
                                </div>
                            </template>
                        </el-scrollbar>
                    </div>
                </div>
            </template>
        </div>
    </Teleport>
</template>

<script>
import { defineComponent, ref, unref, computed, nextTick } from 'vue'
import { useWindowSize, useElementBounding, onClickOutside } from '@vueuse/core'
import { useEditStore } from '@/store'
import useWidget from '@/libs/edit/widgetData'
import useWidgetSetting from '@/libs/edit/widgetSetting'
import usePageHistory from '@/libs/edit/pageHistory'
import { openWidgetAnimationsSetting } from '@/components/edit/widget-animations-setting'
import { onOpenContextmenuEvent } from './events'

export default defineComponent({
    name: 'WidgetContextmenu',
    setup() {
        const editStore = useEditStore()

        const {
            widgetListFlat,
            onDeleteWidget,
            onCopyWidegt,
            getWidgetLevelStatus,
            onSetWidgetLevel
        } = useWidget()

        const {
            onAlign
        } = useWidgetSetting()

        const {
            onAddPageHistory
        } = usePageHistory()

        const widgetIds = ref([]) // 控件ID集合
        const top = ref([]) // 距上位置
        const left = ref([]) // 距下位置
        const visible = ref(false)
        const contextmenuRef = ref(null)

        const style = computed(() => {
            return {
                left: `${left.value}px`,
                top: `${top.value}px`
            }
        })

        const appData = computed(() => editStore.appData)
        const pageId = computed(() => editStore.pageId)
        const pageList = computed(() => {
            if (pageId.value.indexOf('page') !== 0) {
                return []
            }
            const pageKeys = Object.keys(appData.value).filter(key => {
                return (key.indexOf('page') === 0) && !!appData.value[key].eles
            })
            const list = pageKeys.map(key => ({
                name: appData.value[key].customFeature.name,
                router: appData.value[key].router
            }))
            const currentPageIndex = list.findIndex(item => item.router === pageId.value)
            if (currentPageIndex != -1) {
                const currentPageData = list[currentPageIndex]
                list.splice(currentPageIndex, 1)
                list.unshift(currentPageData)
            }
            return list
        })

        const widget = computed(() => widgetListFlat.value[widgetIds.value[0]])
        const widgetType = computed(() => widget.value?.widgetData?.eles?.type)

        // 是否是一级控件
        const isOneLevelWidget = computed(() => {
            const { widgetData, parentId } = widget.value
            return widgetData && !parentId
        })

        // 是否是自由子控件
        const isFreeWidget = computed(() => widget.value.isFreeWidget)

        // 接收控件菜单打开事件
        onOpenContextmenuEvent(data => {
            visible.value = true
            widgetIds.value = data.widgetIds // 控件ID集合
            nextTick(() => {
                const newPosition = getElementPosition(data.left, data.top)
                left.value = newPosition.left // 距下位置
                top.value = newPosition.top // 距上位置
            })

            // 点击组件外部
            onClickOutside(contextmenuRef, () => {
                onClose()
            })
        })

        const getElementPosition = (x, y) => {
            let domLeft = x
            let domTop = y
            const elSize = useElementBounding(contextmenuRef)
            const winSize = useWindowSize()
            // 避免碰壁
            if (domLeft + unref(elSize.width) > unref(winSize.width)) domLeft -= unref(elSize.width)
            if (domTop + unref(elSize.height) > unref(winSize.height)) domTop -= unref(elSize.height)
            return {
                left: domLeft,
                top: domTop
            }
        }

        // 关闭菜单
        const onClose = () => {
            visible.value = false
        }

        // 复制
        const onCopy = (toPageId = pageId.value) => {
            onCopyWidegt({
                toPageId,
                widgetIds: widgetIds.value
            })
            onClose()
        }
        
        // 删除
        const onDelete = () => {
            onDeleteWidget(widgetIds.value)
            onAddPageHistory()
            onClose()
        }

        // // 是否锁定
        // const isLock = computed(() => {
        //     return widgetIds.value.every(id => !!widgetListFlat.value[id].widgetData.eles.customFeature.isLockWidget)
        // })
        // // 锁定/解锁(true锁定 false解锁)
        // const onLockOrUnLock = (status = true) => {
        //     widgetIds.value.forEach(id => {
        //         const widgetData = widgetListFlat.value?.[id]?.widgetData
        //         if (!!widgetData) widgetData.eles.customFeature.isLockWidget = status
        //     })
        //     onClose()
        // }

        // 是否置顶
        const isTop = computed(() => getWidgetLevelStatus(widgetIds.value) === 'top')

        // 是否置底
        const isBottom = computed(() => getWidgetLevelStatus(widgetIds.value) === 'bottom')

        // 置顶/置底(true置顶 false置底)
        const onTopOrBottom = (status = true) => {
            onSetWidgetLevel({
                widgetIds: widgetIds.value,
                type: status ? 'top' : 'bottom'
            })
            onClose()
        }

        // 上移一层/下移一层(true上移一层 false下移一层)
        const onTopOneOrBottomOne = (status = true) => {
            onSetWidgetLevel({
                widgetIds: widgetIds.value,
                type: status ? 'moveup' : 'movedown',
                step: 1
            })
            onClose()
        }

        // 动画
        const onAnimation = () => {
            openWidgetAnimationsSetting({
                data: widget.value.widgetData.eles.animations,
                onConfirm: data => {
                    widget.value.widgetData.eles.animations = data
                }
            })
            onClose()
        }

        // 设置控件对齐(left左对齐，vertical水平居中对齐，right右对齐，top顶对齐， horizontal垂直居中对齐，bottom底对齐)
        const onSetAlign = type => {
            onAlign(widgetIds.value, type)
            onAddPageHistory()
            onClose()
        }

        return {
            visible,
            contextmenuRef,
            pageId,
            pageList,
            widgetType,
            isOneLevelWidget,
            isFreeWidget,
            style,

            onClose,

            // isLock,
            isTop,
            isBottom,

            onCopy,
            onDelete,
            // onLockOrUnLock,
            onTopOrBottom,
            onTopOneOrBottomOne,
            onAnimation,
            onSetAlign
        }
    }
})
</script>

<style lang="less" scoped>
@import './widget-contextmenu.less';
</style>